package com.api.gc;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.gc.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.admincenter.file.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Tyc
 * @create 2024/03/29
 * @description
 */
@Path("/export")
public class ExportData {
    private Logger logger = LoggerFactory.getLogger(GCExportData.class);


    private static final String INPUT_TIME_FORMAT_2 = "yyyy-MM-dd";

    private static final String OUTPUT_TIME_FORMAT = "yyyy/MM/dd";

    public static String validateAndFormat(String inputTime) {
        try {
            // 创建用于解析输入时间的 SimpleDateFormat 对象
            SimpleDateFormat inputParser = new SimpleDateFormat(INPUT_TIME_FORMAT_2);

            // 尝试解析输入字符串
            Date parsedDate = inputParser.parse(inputTime);

            // 创建用于格式化目标时间的 SimpleDateFormat 对象
            SimpleDateFormat outputFormatter = new SimpleDateFormat(OUTPUT_TIME_FORMAT);

            // 格式化解析得到的日期为所需格式
            String formattedTime = outputFormatter.format(parsedDate);

            return formattedTime.trim();
        } catch (ParseException e) {
            // 解析过程中发生异常，说明输入字符串不是有效的时间格式
            System.err.println("Invalid time format: " + inputTime);
            return inputTime.trim();
        }
    }
    @Path("/exportData")
    @POST
    @Produces(MediaType.APPLICATION_JSON)//返回方式为JSON
    public Result exportData( @Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
        try{
            String datas = request.getParameter("datas");
            JSONArray jsonArray = JSON.parseArray(datas);
            String templateid = request.getParameter("templateid");
            File newFile = null;
            String newFileName = null;
            if (StringUtils.isBlank(templateid)){
                //如果模板id为空 则按照显示列生成模板并注入数据
                newFileName = UUID.fastUUID()+".xls";
                String tempFileName = UUID.fastUUID()+".xls";
                newFile = new File("/data/unstructured/template/tempFile/"+tempFileName);
                newFile.createNewFile();
                File init = new File("/data/unstructured/template/tempFile/INIT.xls");
                FileUtil.copyFile(init, newFile);
                File newFile2 = new File("/data/unstructured/template/tempFile/"+newFileName);
                String titles = request.getParameter("titles");
                System.out.println("titles:"+titles);
                List<String> titleList = Arrays.asList(titles.split(","));
                FileInputStream fis = new FileInputStream(newFile);
                Workbook workbook = new HSSFWorkbook(fis);
                Sheet sheet = workbook.getSheetAt(0);
                Row newRow = sheet.createRow(0);
                for (int j = 0; j < titleList.size(); j++) {
                    String key = titleList.get(j);
                    Cell cell = newRow.createCell(j);
                    key = key.replaceAll("[\\s\\u00A0]+","").trim();
                    cell.setCellValue(key.trim());
                    //创建单元格样式
                    cell.setCellType(CellType.STRING);
                }
                System.out.println("重新添加一行作为新的第一行:");
                List<String> realFieldNameList = new LinkedList<>();
                for (String item : titleList) {
                    String realFieldName = item.split("-")[1];//取出字段名
                    realFieldNameList.add(realFieldName);
                }
                System.out.println("批量插入指定模板excel:");
                //批量插入指定模板excel
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    Row row = sheet.createRow(i+1);
                    for (int j = 0; j < realFieldNameList.size(); j++) {
                        String key = realFieldNameList.get(j);
                        Cell cell = row.createCell(j);
                        String val = "";
                        if (item.get(key)!=null){
                            val = String.valueOf(item.get(key));
                            val = val.replaceAll("[\\s\\u00A0]+","").trim();
                        }
                        cell.setCellValue(validateAndFormat(val));
                        //创建单元格样式
                        cell.setCellType(CellType.STRING);
                    }
                }
                System.out.println("生成excel");
                // 保存更改到新文件
                try (FileOutputStream fos = new FileOutputStream(newFile2)) {
                    workbook.write(fos);
                }finally {
                    workbook.close();
                    fis.close();
                }
                return Result.ok("生成成功!",newFileName);
                /*try (FileOutputStream fos = new FileOutputStream(newFile)) {//将表头写入
                    workbook.write(fos);
                }*/
            }else{
                File file = new File("/data/unstructured/template/"+templateid+getFileExtension(templateid));
                newFileName = UUID.fastUUID()+getFileExtension(templateid);
                newFile = new File("/data/unstructured/template/tempFile/"+ newFileName);
                newFile.createNewFile();
                FileUtil.copyFile(file, newFile);
                FileInputStream fis = new FileInputStream(newFile);
                Workbook workbook = null;// 打开已存在的Excel文件
                if (".xls".equals(getFileExtension(templateid))) {
                    workbook = new HSSFWorkbook(fis);
                } else if (".xlsx".equals(getFileExtension(templateid))) {
                    workbook = new XSSFWorkbook(fis);
                } else {
                    return Result.error("生成失败!文件格式不符");
                }
                if (jsonArray.size()==0){
                    // 保存更改到原文件
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        workbook.write(fos);
                    }
                    return Result.ok("生成成功!",newFileName);
                }
                Sheet sheet = workbook.getSheetAt(0); // 根据名称获取工作表
                Row titleRow = sheet.getRow(0);//获取标题列  然后解析标题列的字段名
                List<String> realFieldNameList = new LinkedList<>();
                for (Cell cell : titleRow) {
                    String fieldName = cell.getStringCellValue();
                    String realFieldName = fieldName.split("-")[1];//取出字段名
                    realFieldNameList.add(realFieldName);
                }
                //批量插入指定模板excel
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    Row row = sheet.createRow(i+1);
                    for (int j = 0; j < realFieldNameList.size(); j++) {
                        String key = realFieldNameList.get(j);
                        Cell cell = row.createCell(j);
                        String val = "";
                        if (item.get(key)!=null){
                            val = String.valueOf(item.get(key));
                            //针对时间格式 进行格式化
                            val = val.replaceAll("[\\s\\u00A0]+","").trim();
                        }
                        cell.setCellValue(validateAndFormat(val));
                        //创建单元格样式
                        cell.setCellType(CellType.STRING);
                    }
                }
                // 保存更改到原文件
                try (FileOutputStream fos = new FileOutputStream(newFile)) {
                    workbook.write(fos);
                }finally {
                    workbook.close();fis.close();
                }
                return Result.ok("生成成功!",newFileName);
            }
            //writeBytes(newFile, response.getOutputStream());
            //newFile.delete();
        }catch (Exception ex){
            System.out.println("生成失败!:"+ex.getMessage());
            ex.printStackTrace();
            return Result.error("生成失败!");
        }
    }

    public static void setAttachmentResponseHeader(HttpServletRequest request,HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")||agent.contains("Trident"))
        {
            realFileName = URLEncoder.encode(realFileName, "UTF-8");
        }
        else
        {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(realFileName.getBytes("UTF-8"), "UTF-8") + "\"");
            realFileName = new String(realFileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        String extension = "";

        int i = realFileName.lastIndexOf('.');
        if (i > 0) {
            extension = realFileName.substring(i+1); // 获取后缀名
        }
        if (extension.equals("xls")){
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");
        }else if (extension.equals("xlsx")){
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + realFileName );
        response.setHeader("download-filename", realFileName);
        response.setHeader("Connection", "close");
    }

    /**
     * 获得模板的后缀
     * @param templateid
     * @return
     */
    public String getFileExtension(String templateid) {
        File file1 = new File("/data/unstructured/template/"+templateid+".xls");
        File file2 = new File("/data/unstructured/template/"+templateid+".xlsx");
        if (file1.exists()){
            return ".xls";
        }else if (file2.exists()){
            return ".xlsx";
        }else{
            return "";
        }
    }
}
